package com.example.testgame.handlers;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.example.testgame.sys.Constant;
import com.example.testgame.sys.Variable;
import com.example.testgame.util.GameHelper;
import com.example.testgame.util.ScreenUtil;
/**
 * 滚动控制的Handler
 * @author wolf_jr
 *
 */
public class ScrollHandler extends Handler {
	
	private static final long INTERVAL = 20;
	
	private static ScrollHandler instance = new ScrollHandler();
	
	private List<OnScrollChangeListener> listenerList;
	
	private ScrollHandler() {
		listenerList = new ArrayList<ScrollHandler.OnScrollChangeListener>();
	}
	
	@Override
	public void handleMessage(Message msg) {
		int col = msg.arg1;
		int row = msg.arg2;
		Context ctx = (Context) msg.obj;
		int goalX = (int) (ScreenUtil.screen_width(ctx) / 2 - ((col + 0.5) * Constant.BLOCK_WIDTH * Variable.zoom));
		int goalY = (int) (ScreenUtil.screen_height(ctx) / 2 - ((row + 0.5) * Constant.BLOCK_HEIGHT * Variable.zoom));
		boolean hadChange = false;
		if(goalX != Variable.offsetX) {
			hadChange = true;
			int dx = goalX - Variable.offsetX;
			int _dx;
			if(Math.abs(dx) > 1) {
				_dx = dx / 4;
				if(Math.abs(_dx) < 1) {
					_dx = dx > 0? 1: -1;
				}
			}else {
				_dx = dx;
			}
			Variable.offsetX += _dx;
		}
		if(goalY != Variable.offsetY) {
			hadChange = true;
			int dy = goalY - Variable.offsetY;
			int _dy;
			if(Math.abs(dy) > 2) {
				_dy = dy / 4;
				if(Math.abs(_dy) < 2) {
					_dy = dy > 0? 2: -2;
				}
			}else {
				_dy = dy;
			}
			Variable.offsetY += _dy;
		}
		System.out.println("x,y: " + Variable.offsetX + "," + Variable.offsetY);
		if(hadChange) {
			notifyScrollChanged();
			Message _msg = obtainMessage(0, msg.arg1, msg.arg2);
			sendMessageDelayed(_msg, INTERVAL);
		}
	}
	
	private void notifyScrollChanged() {
		for (OnScrollChangeListener listener : listenerList) {
			listener.onScrollChange();
		}
	}
	
	public synchronized static void startScrollTo(Context ctx, int x, int y) {
		instance.removeMessages(0);
		Message msg = instance.obtainMessage(0, GameHelper.getColByX(x), GameHelper.getRowByY(y), ctx);
		instance.sendMessage(msg);
	}
	
	/**
	 * 添加滚动改变时的监听
	 * @param listener
	 */
	public static void addOnScrollChangeListener(OnScrollChangeListener listener) {
		if(listener != null) {
			instance.listenerList.add(listener);
		}
	}
	
	
	/**
	 * 滚动改变时的回调
	 * @author wolf_jr
	 *
	 */
	public static interface OnScrollChangeListener {
		void onScrollChange();
	}

}
